﻿using LdtDataEngin.ModuleDetail.AnalysisModule.SituationPlot;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.SituationPloModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.CommonModule.PersonMerger
{
    public class SituationPlotData
    {
        /// <summary>
        /// 上下文信息
        /// </summary>
        public DataContext dataContext { get; set; }
        /// <summary>
        /// 案由信息获取
        /// </summary>
        public GetSysCaseCause dALSYS_CaseCause = new GetSysCaseCause();

        /// <summary>
        /// 情形情节合并信息
        /// </summary>
        public void Merge()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };

            foreach (var dataModelResults in dataContext.DataLayerAns.ElementAnalsisDataModelResults)
            {
                List<DataModel> dataModelList = dataModelResults.Value;

                //分割事实要素
                List<DataModel> dataModelFackList = dataModelList.Where(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "事实要素")?.ToList();
                foreach (DataModel modelRoot in dataModelFackList)
                {
                    dataModelList = xmlUtilCommon.SubordinateDataModelList(dataModelList, modelRoot);
                    //获取相关情形情节节点信息
                    List<DataModel> relevantDataModelList = dataModelList.Where(a => a.XmlPath.IndexOf("相关情形情节") > -1)?.ToList();

                    //犯罪行为情形情节存在则进行合并否则不执行
                    if (relevantDataModelList != null && relevantDataModelList.Count > 0)
                    {
                        List<SituationModel> crimeSituationModelList = new List<SituationModel>();
                        List<SituationModel> relevantSituationModelList = new List<SituationModel>();

                        DataModel relevantDataMode = relevantDataModelList.FirstOrDefault(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "相关情形情节");
                        if (relevantDataMode != null)
                        {
                            List<DataModel> relevantDetildataModelList = relevantDataModelList.Where(a => a.ParentId == relevantDataMode.ID)?.ToList();
                            if (relevantDetildataModelList != null)
                            {
                                foreach (DataModel detilDataModel in relevantDetildataModelList)
                                {
                                    List<DataModel> dataRModelList = xmlUtilCommon.SubordinateDataModelList(relevantDataModelList, detilDataModel);
                                    XmlDocument xmlDocument = xmlUtilCommon.DataModelByXml(dataRModelList, detilDataModel.ParentId);
                                    SituationModel situationModel = XmlUtility.DeserializeToObject<SituationModel>(xmlDocument.OuterXml);
                                    relevantSituationModelList.Add(situationModel);
                                }
                            }
                            DataModel dataModelRole = dataModelList.FirstOrDefault(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "主张方");
                            string suitID = "";
                            if (dataModelRole != null)
                            {
                                if (dataModelRole.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位") != null)
                                {
                                    suitID = dataModelRole.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                }
                            }
                            UpMerge(crimeSituationModelList, relevantSituationModelList, suitID);
                            foreach (var relevanModel in relevantSituationModelList)
                            {
                                string xml = XmlUtility.SerializeToXmlNew<SituationModel>(relevanModel);
                                DataModel dataModelRoot = dataModelResults.Value.FirstOrDefault(a => a.ID == relevanModel.Id);
                                List<DataModel> dataModelRootList = xmlUtilCommon.SubordinateDataModelList(dataModelResults.Value, dataModelRoot);
                                XmlDocument document1 = xmlUtilCommon.DataModelByXml(dataModelResults.Value, "");
                                foreach (DataModel model in dataModelRootList)
                                {
                                    dataModelResults.Value.Remove(model);
                                }
                                XmlDocument document2 = xmlUtilCommon.DataModelByXml(dataModelResults.Value, "");
                                XmlDocument xmldetile = new XmlDocument();
                                xmldetile.LoadXml(xml);
                                List<DataModel> dataModelADDList = xmlUtilCommon.GetXMLByDataModelBackID(xmldetile).dataModelList;
                                DataModel dataModelRest = dataModelResults.Value.FirstOrDefault(a => a.ID == dataModelRoot.ParentId);
                                foreach (DataModel model in dataModelADDList)
                                {
                                    model.XmlPath = dataModelRest.XmlPath + "/" + model.XmlPath;
                                }
                                dataModelADDList.FirstOrDefault(a => a.ParentId == "").ParentId = dataModelRoot.ParentId;
                                dataModelResults.Value.AddRange(dataModelADDList);
                            }
                            XmlDocument document = xmlUtilCommon.DataModelByXml(dataModelResults.Value, "");
                            dataContext.InteractiveShow.LogShow("情形情节合并后结果：" + document.OuterXml);
                        }

                    }
                }
            }

          
        }


        /// <summary>
        /// 情形情节合并
        /// </summary>
        /// <param name="sitauionPloConfig">合并配置信息</param>
        /// <param name="plotExcluConfig">通用情节排除配置</param>
        public void PreferredMerge(string sitauionPloConfig,string plotExcluConfig) 
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };

            if (dataContext.DataLayerOpt.MergeElementDataList == null)
            {
                dataContext.DataLayerOpt.MergeElementDataList =new Dictionary<string, List<DataModel>>();
            }
            if (dataContext.DataLayerOpt != null && !string.IsNullOrEmpty(sitauionPloConfig) && dataContext.DataLayerAns.StageProcessAnalysisDataModel != null && dataContext.DataLayerOpt.MergeElementDataList != null)
            {
                //案件要素信息加载--当前阶段的信息
                SituationPloMerge situationPloMerge = XmlUtility.DeserializeToObject<SituationPloMerge>(sitauionPloConfig);
                CommonPlotExclusionModel plotExclusion= XmlUtility.DeserializeToObject<CommonPlotExclusionModel>(plotExcluConfig);
                var casemodle = situationPloMerge.situationPloCaseModelList.FirstOrDefault(a => a.CaseType == dataContext.DataLayerOpt.CaseType);
                if (casemodle!=null)
                {
                    DataModel caseDataModel = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", dataContext.DataLayerAns.StageProcessAnalysisDataModel.path);
                    List<DataModel> caseDataModelSubteList = xmlUtilCommon.SubParentDateModelNoDM(dataContext.DataLayerOpt.SourdatModleList, caseDataModel);
                    List<DataModel> caseDataModelDinateList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, caseDataModel);
                    List<DataModel> caseDataModelList = new List<DataModel>();
                    caseDataModelList.AddRange(caseDataModelSubteList);
                    caseDataModelList.AddRange(caseDataModelDinateList);

                    //合并后要素中情形情节信息
                    List<SituationModel> relevantSituationModelList = new List<SituationModel>();
                    //公诉意见信息
                    List<SituationModel> LStatusPlotModelList = new List<SituationModel>();
                    //结果集合
                    List<SituationModel> ResultStatusPlotModelList = new List<SituationModel>();
                    //理由情形情节
                    List<SituationModel> CStatusPlotpathModelList = new List<SituationModel>();
                    if (casemodle != null)
                    {
                        foreach (var mergerelement in dataContext.DataLayerOpt.MergeElementDataList)
                        {
                            var cuasemodel = casemodle.situationPloCauseModelList.FirstOrDefault(a => a.Causeid == mergerelement.Key);
                            if (cuasemodel!=null)
                            {

                         
                            //案由信息加载 排尔哈提·亚尔艾力 排尔哈提·亚尔艾力
                            
                            List<DataModel> cuaseDataModelList = XmlUtility.ConditionDataModelList(mergerelement.Value, "", cuasemodel.CauseStatusPlotpath);
                            List<SituationModel> dataMergerList = new List<SituationModel>();
                            //合并后要素中情形情节信息赋值
                            SetSituationModel(mergerelement.Value, cuaseDataModelList, dataMergerList);
                            UpMerge(dataMergerList, relevantSituationModelList);
                                if (relevantSituationModelList!=null && relevantSituationModelList.Count>0)
                                {
                                    foreach (var rele in relevantSituationModelList)
                                    {
                                        if (rele.situationList!=null && rele.situationList.Count>0)
                                        {
                                            foreach (var sit in rele.situationList)
                                            {
                                                if (string.IsNullOrEmpty(sit.zmid))
                                                {
                                                    sit.zmid = mergerelement.Key;
                                                }
                                                
                                            }
                                        }
                                        if (rele.plotModelList!=null && rele.plotModelList.Count>0)
                                        {
                                            foreach (var plot in rele.plotModelList)
                                            {
                                                if (string.IsNullOrEmpty(plot.zmid))
                                                {
                                                    plot.zmid = mergerelement.Key;
                                                }
                                               
                                            }
                                        }
                                    }
                                }
                                
                            }
                        }
                        
                    }
                    //公诉意见要素中情形情节信息赋值
                    List<DataModel> LStatusPlotDataModelList = new List<DataModel>();
                    if (!string.IsNullOrEmpty(casemodle.LStatusPlotpath))
                        LStatusPlotDataModelList = XmlUtility.ConditionDataModelList(caseDataModelList, "", casemodle.LStatusPlotpath);
                    SetSituationModel(caseDataModelList, LStatusPlotDataModelList, LStatusPlotModelList);
                    //结果集合
                    List<DataModel> ResultStatusPlotDataModelList = XmlUtility.ConditionDataModelList(caseDataModelList, "", casemodle.StatusPlotpath);
                    SetSituationModel(caseDataModelList, ResultStatusPlotDataModelList, ResultStatusPlotModelList);
                    //结果集合
                    List<DataModel> CStatusPlotpathDataModelList = XmlUtility.ConditionDataModelList(caseDataModelList, "", casemodle.CStatusPlotpath);
                    SetSituationModel(caseDataModelList, CStatusPlotpathDataModelList, CStatusPlotpathModelList);
                    UpMerge(relevantSituationModelList, ResultStatusPlotModelList);
                    UpMerge(LStatusPlotModelList, ResultStatusPlotModelList);
                    UpMerge(CStatusPlotpathModelList, ResultStatusPlotModelList);
                  //情形情节有ID没有名称的从案由表补充名称，没有来源的默认添加来源
                    ResultStatusPlotModelList.ForEach(x=> {
                        if (x.situationList.Any())
                        {
                            x.situationList.ForEach(y => {
                                if (y.situationList.Any())
                                {
                                    y.situationList.ForEach(z => {

                                        if (!string.IsNullOrWhiteSpace(z.SituationID)&&string.IsNullOrWhiteSpace(z.SituationName))
                                        {
                                            z.SituationName =dALSYS_CaseCause.GetModel(z.SituationID)?.CC_Name;                                            
                                        }
                                        if (string.IsNullOrWhiteSpace(z.Qxly))
                                        {
                                            z.Qxly = "investigate";
                                        }
                                    });
                                }
                            });                        
                        }
                        if (x.plotModelList.Any())
                        {
                            x.plotModelList.ForEach(y => {
                                if (y.plotDetilModelList.Any())
                                {
                                    y.plotDetilModelList.ForEach(z => {

                                        if (!string.IsNullOrWhiteSpace(z.PlotID) && string.IsNullOrWhiteSpace(z.PlotName))
                                        {
                                            z.PlotName = dALSYS_CaseCause.GetModel(z.PlotID)?.CC_Name;
                                        }
                                        if (string.IsNullOrWhiteSpace(z.Qjly))
                                        {
                                            z.Qjly = "investigate";
                                        }
                                    });
                                }
                            });
                        }
                    });
                    //计算组合情形组合表述
                    if (ResultStatusPlotModelList.Count > 0)
                    {
                        foreach (var mode in ResultStatusPlotModelList)
                        {
                            List<string> IDList = new List<string>();
                            if (mode.situationList.Count > 0)
                            {
                                foreach (var situationItem in mode.situationList)
                                {
                                    string situationly = "";
                                    if (situationItem.situationList.FirstOrDefault(a => a.Qxly?.ToLower() == "convicted") != null)
                                    {
                                        situationly = "convicted";
                                    }
                                    else if (situationItem.situationList.FirstOrDefault(a => a.Qxly?.ToLower() == "legation") != null)
                                    {
                                        situationly = "legation";
                                    }
                                    else if (situationItem.situationList.FirstOrDefault(a => a.Qxly?.ToLower() == "investigate") != null)
                                    {
                                        situationly = "investigate";
                                    }
                                    else if (situationItem.situationList.FirstOrDefault(a => a.Qxly?.ToLower() == "defense") != null)
                                    {
                                        situationly = "defense";
                                    }
                                    if (!string.IsNullOrEmpty(situationly))
                                    {
                                        foreach (var detailItem in situationItem.situationList.Where(a => a.Qxly == situationly))
                                        {
                                            IDList.Add(detailItem.SituationID);
                                        }
                                        SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                                        string situationID = situationExpressAdd.GetGroupSituationID("1", 1, "1", IDList);
                                        ///根据组合情节获取表述ID
                                        string ew_id = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType, true);
                                        situationItem.SituationID = situationID;
                                        situationItem.Ewid = ew_id;
                                    }
                                }
                            }
                        }
                    }

                    if (ResultStatusPlotModelList.Count > 0)
                    {
                        foreach (var mode in ResultStatusPlotModelList)
                        {
                            List<string> IDList = new List<string>();
                            if (mode.plotModelList !=null && mode.plotModelList.Any())
                            {
                                foreach (var plotItem in mode.plotModelList)
                                {
                                    //罪名ID
                                    string zmid = plotItem.zmid;
                                    //获取当前罪名ID下需要排除的情节Id
                                    List<string> exclusionIds = new List<string>();
                                    if(!string.IsNullOrWhiteSpace(zmid) && plotExclusion!=null && plotExclusion.Causes!=null)
                                    {
                                        var excluCause = plotExclusion.Causes.FirstOrDefault(x => x.CauseId == zmid);
                                        if(excluCause!=null && excluCause.Exclude!=null)
                                        {
                                            var legalPlot = excluCause.Exclude.LegalPlot;
                                            if(legalPlot!=null)
                                            {
                                                var legalIds= legalPlot.Details.Select(x => x.CCID).ToList();
                                                if (legalIds != null && legalIds.Any())
                                                    exclusionIds.AddRange(legalIds);
                                            }

                                            var discretionPlot = excluCause.Exclude.DiscretionPlot;
                                            if (discretionPlot != null)
                                            {
                                                var discretionIds = discretionPlot.Details.Select(x => x.CCID).ToList();
                                                if (discretionIds != null && discretionIds.Any())
                                                    exclusionIds.AddRange(discretionIds);
                                            }
                                        }
                                    }
                                    if (exclusionIds != null && exclusionIds.Any())
                                        plotItem.plotDetilModelList.RemoveAll(x => exclusionIds.Contains(x.PlotID));
                                    foreach (var detailItem in plotItem.plotDetilModelList)
                                    {
                                        if (!string.IsNullOrEmpty(detailItem.PlotID))
                                        {
                                            IDList = new List<string>();
                                            IDList.Add(detailItem.PlotID);

                                            SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                                            string situationID = situationExpressAdd.GetGroupSituationID(detailItem.PlotID, 1, "1", null);
                                            ///根据组合情节获取表述ID
                                            string ew_id = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType);
                                            detailItem.ewid = ew_id;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    //将合并后的数据赋值
                    foreach (var relevanModel in ResultStatusPlotModelList)
                    {
                        if (relevanModel.Name!=null)
                        {
                            string xml = XmlUtility.SerializeToXmlNew<SituationModel>(relevanModel);
                            DataModel dataModelRoot = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == relevanModel.Id);
                            bool IsRoom = false;
                            if(dataModelRoot!=null)
                            {
                                if (dataModelRoot.AttributesList?.FirstOrDefault(a => a.Name == "姓名或名称") != null)
                                {
                                    AttributeInfo attributeInfo = dataModelRoot.AttributesList.FirstOrDefault(a => a.Name == "姓名或名称");
                                    if (attributeInfo.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue == relevanModel.Name)
                                    {
                                        IsRoom = true;
                                    }
                                }
                                if (IsRoom)
                                {
                                    List<DataModel> dataModelRootList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModelRoot);
                                    XmlDocument document1 = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                                    foreach (DataModel model in dataModelRootList)
                                    {
                                        dataContext.DataLayerOpt.SourdatModleList.Remove(model);
                                    }
                                }
                                XmlDocument xmldetile = new XmlDocument();
                                xmldetile.LoadXml(xml);
                                XmlDocument xmluti = new XmlDocument();
                                xmluti = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                                List<DataModel> dataModelADDList = xmlUtilCommon.GetXMLByDataModelBackID(xmldetile).dataModelList;
                                DataModel dataModelRest = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == dataModelRoot.ParentId);
                                foreach (DataModel model in dataModelADDList)
                                {
                                    model.XmlPath = dataModelRest.XmlPath + "/" + model.XmlPath;
                                }
                                dataModelADDList.FirstOrDefault(a => a.ParentId == "").ParentId = dataModelRoot.ParentId;
                                dataContext.DataLayerOpt.SourdatModleList.AddRange(dataModelADDList);
                            }
                            dataContext.DataLayerOpt.OptimizationXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                        }
                    }
                    //对案由要素进行数据加工处理
                    List<DataModel> caseCausedataModelList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "相关情形情节" && a.XmlPath.IndexOf("案件信息要素中心") == -1)?.ToList();
                    if (dataContext.DataLayerAns.CaseCausesList != null && dataContext.DataLayerAns.CaseCausesList.Count > 0)
                    {
                        caseCausedataModelList = caseCausedataModelList.Where(a => a.XmlPath.IndexOf("案由要素") > -1)?.ToList();
                    }
                    if (caseCausedataModelList != null)
                    {
                        foreach (var causeDatamodel in caseCausedataModelList)
                        {
                            List<DataModel> casuseTempDataList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, causeDatamodel);
                            var detailDataList = casuseTempDataList.Where(a => a.AttributesList.FirstOrDefault(c => c.Name == "情形ID" || c.Name == "情节ID") != null)?.ToList();
                            if (detailDataList != null)
                            {
                                foreach (var item in detailDataList)
                                {
                                    List<AttributeInfo> attinfos = item.AttributesList.Where(a => a.Name == "情形ID" || a.Name == "情节ID" || a.Name == "原文").ToList();
                                    if(attinfos!=null && attinfos.Any())
                                    {
                                        item.AttributesList = new List<AttributeInfo>();
                                        item.AttributesList.AddRange(attinfos);
                                    }
                                }
                            }
                            var detailParentDataList = casuseTempDataList.Where(a => a.AttributesList.FirstOrDefault(c => c.Name == "组合情形ID" || c.Name == "组合表述") != null)?.ToList();
                            if (detailParentDataList != null)
                            {
                                foreach (var item in detailParentDataList)
                                {
                                    AttributeInfo attributenode = item.AttributesList.FirstOrDefault(a => a.Name.IndexOf("组合情形") > -1 || a.Name.IndexOf("组合表述") > -1);
                                    if (attributenode != null)
                                    {
                                        item.AttributesList.Remove(attributenode);
                                    }
                                }
                            }
                        }
                    }
                    dataContext.DataLayerOpt.OptimizationXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                }
               
            }
        }

        /// <summary>
        /// 对情形情节实体进行赋值
        /// </summary>
        /// <param name="ResultDataModeList">总体XML实体</param>
        /// <param name="RootDataModelList">根节点合集</param>
        /// <param name="situationModelList">返回值</param>
        private void SetSituationModel(List<DataModel> ResultDataModeList, List<DataModel> RootDataModelList, List<SituationModel> situationModelList)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            if (RootDataModelList != null && RootDataModelList.Count > 0)
            {
                foreach (DataModel cuaseDataModel in RootDataModelList)
                {
                    List<DataModel> dataRModelList = xmlUtilCommon.SubordinateDataModelList(ResultDataModeList, cuaseDataModel);
                    XmlDocument xmlDocument = xmlUtilCommon.DataModelByXml(dataRModelList, cuaseDataModel.ParentId);

                    SituationModel situationModel = XmlUtility.DeserializeToObject<SituationModel>(xmlDocument.OuterXml);
                    situationModelList.Add(situationModel);
                }
            }
        }

        /// <summary>
        /// 对合并结果进行分组
        /// </summary>
        /// <param name="situationModelList"></param>
        public void SituaModelOrerdBy(List<SituationModel> situationModelList)
        {
            foreach (SituationModel situationModel in situationModelList)
            {
                //情形信息
                List<PlotModel> plotModelList = situationModel.plotModelList;
                //情节信息
                List<Situation> situationList = situationModel.situationList;

                foreach (PlotModel plotModel in plotModelList)
                {
                    List<PlotDetilModel> plotDetilModelList = plotModel.plotDetilModelList;
                    if (plotDetilModelList.Count > 0)
                    {
                        foreach (var ploTitem in plotDetilModelList)
                        {
                            PlotDetilModel model = ploTitem;
                            if (model.Qjly.ToLower() == "convicted")
                            {
                                model.LyNumber = 4;
                            }
                            if (model.Qjly.ToLower() == "legation")
                            {
                                model.LyNumber = 3;
                            }
                            if (model.Qjly.ToLower() == "investigate")
                            {
                                model.LyNumber = 2;
                            }
                            if (model.Qjly.ToLower() == "defense")
                            {
                                model.LyNumber = 1;
                            }
                        }

                        plotDetilModelList = plotDetilModelList.OrderByDescending(a => a.LyNumber).ToList();
                        PlotDetilModel plotmodel = plotDetilModelList.First();
                        //高优先级数据集
                        List<PlotDetilModel> plotDetiRunlList = plotDetilModelList.Where(a => a.LyNumber == plotmodel.LyNumber).ToList();
                        foreach (var plotItem in plotDetiRunlList)
                        {
                            plotDetilModelList.Remove(plotItem);
                        }
                        var plotGropList = plotDetilModelList.GroupBy(a => new { a.LyNumber }, a => a);
                        foreach (var plotGrop in plotGropList)
                        {
                            //低优先级情形情节组
                            List<PlotDetilModel> plotDetiDesclList = plotGrop.ToList();
                            foreach (var runmdoel in plotDetiRunlList)
                            {
                                var model = plotDetiDesclList.FirstOrDefault(a => a.PlotID == runmdoel.PlotID);
                                if (model != null)
                                {
                                    runmdoel.Qjrdjg = model.Qjrdjg;
                                }
                            }
                            foreach (var runmdoel in plotDetiDesclList)
                            {
                                var model = plotDetiRunlList.FirstOrDefault(a => a.PlotID == runmdoel.PlotID);
                                if (model == null)
                                {
                                    PlotDetilModel plotDetilModel = new PlotDetilModel();
                                    plotDetilModel.Id = "";
                                    plotDetilModel.ewid = runmdoel.ewid;
                                    plotDetilModel.Influencetypeid = runmdoel.Influencetypeid;
                                    plotDetilModel.LyNumber = runmdoel.LyNumber;
                                    plotDetilModel.PoType = runmdoel.PoType;
                                    plotDetilModel.Qjly = plotDetiRunlList[0].Qjly;
                                    plotDetilModel.Qjrdjg = "0";
                                    plotDetilModel.PlotID = runmdoel.PlotID;
                                    plotDetilModel.PlotName = runmdoel.PlotName;
                                    plotDetilModel.plotOrgtextList = runmdoel.plotOrgtextList;
                                    plotDetiRunlList.Add(plotDetilModel);
                                }
                            }
                        }
                        plotDetilModelList.AddRange(plotDetiRunlList);
                        plotModel.plotDetilModelList = plotDetilModelList;
                    }

                }


                foreach (Situation situation in situationList)
                {
                    List<SituationDetil> situationDetilList = situation.situationList;
                    if (situationDetilList.Count > 0)
                    {
                        foreach (var ploTitem in situationDetilList)
                        {
                            SituationDetil model = ploTitem;
                            if (model.Qxly.ToLower() == "convicted")
                            {
                                model.LyNumber = 4;
                            }
                            if (model.Qxly.ToLower() == "legation")
                            {
                                model.LyNumber = 3;
                            }
                            if (model.Qxly.ToLower() == "investigate")
                            {
                                model.LyNumber = 2;
                            }
                            if (model.Qxly.ToLower() == "defense")
                            {
                                model.LyNumber = 1;
                            }
                        }
                        situationDetilList = situationDetilList.OrderByDescending(a => a.LyNumber).ToList();
                        SituationDetil situatmodel = situationDetilList.First();
                        //高优先级数据集
                        List<SituationDetil> plotDetiRunlList = situationDetilList.Where(a => a.LyNumber == situatmodel.LyNumber).ToList();
                        foreach (var plotItem in plotDetiRunlList)
                        {
                            situationDetilList.Remove(plotItem);
                        }

                        var plotGropList = situationDetilList.GroupBy(a => new { a.LyNumber }, a => a);
                        foreach (var plotGrop in plotGropList)
                        {
                            //低优先级情形情节组
                            List<SituationDetil> plotDetiDesclList = plotGrop.ToList();
                            foreach (var runmdoel in plotDetiRunlList)
                            {
                                var model = plotDetiDesclList.FirstOrDefault(a => a.SituationID == runmdoel.SituationID);
                                if (model != null)
                                {
                                    runmdoel.Qxrdjg = model.Qxrdjg;
                                }
                            }
                            foreach (var runmdoel in plotDetiDesclList)
                            {
                                var model = plotDetiRunlList.FirstOrDefault(a => a.SituationID == runmdoel.SituationID);
                                if (model == null)
                                {
                                    SituationDetil situationDetil = new SituationDetil();
                                    situationDetil.Id = "";
                                    situationDetil.LyNumber = runmdoel.LyNumber;
                                    situationDetil.Qxly = plotDetiRunlList[0].Qxly;
                                    situationDetil.Qxrdjg = "0";
                                    situationDetil.SituationID = runmdoel.SituationID;
                                    situationDetil.SituationName = runmdoel.SituationName;
                                    situationDetil.situationOrgtextList = runmdoel.situationOrgtextList;
                                    plotDetiRunlList.Add(situationDetil);
                                }
                            }
                        }
                        situationDetilList.AddRange(plotDetiRunlList);
                        situation.situationList = situationDetilList;
                    }

                }

            }
        }

        /// <summary>
        /// 情形情节合并方法
        /// </summary>
        /// <param name="crimeSituationModelList">被合并的数据集</param>
        /// <param name="relevantSituationModelList">结果数据集</param>
        /// <param name="suitID">结果数据集</param>
        public void UpMerge(List<SituationModel> crimeSituationModelList, List<SituationModel> relevantSituationModelList, string suitID = "")
        {

            foreach (SituationModel crimeDataModel in crimeSituationModelList)
            {
                if (relevantSituationModelList.FirstOrDefault(a => a.Name == crimeDataModel.Name) != null)
                {
                    string suitid = "";
                    SituationModel relevantSituationModel = relevantSituationModelList.FirstOrDefault(a => a.Name == crimeDataModel.Name);
                    if (relevantSituationModel != null)
                    {
                        if (string.IsNullOrEmpty(suitID))
                        {
                            suitID = crimeDataModel.suitID;
                        }

                        if (!string.IsNullOrEmpty(suitID))
                        {
                            if (suitID == "306")
                            {
                                suitid = "investigate";
                            }
                            else if (suitID == "164")
                            {
                                suitid = "legation";
                            }
                            else if (suitID == "1")
                            {
                                suitid = "defense";
                            }
                        }
                    }
                    //对数据来源进行赋值
                    if (!string.IsNullOrEmpty(suitid))
                    {
                        foreach (var situation in crimeDataModel.situationList)
                        {
                            foreach (var modeItme in situation.situationList)
                            {
                                if (string.IsNullOrWhiteSpace(modeItme.Qxly))
                                {
                                    modeItme.Qxly = suitid;
                                }
                                
                            }
                        }

                        foreach (var situation in crimeDataModel.plotModelList)
                        {
                            foreach (var modeItme in situation.plotDetilModelList)
                            {
                                if (string.IsNullOrWhiteSpace(modeItme.Qjly))
                                {
                                    modeItme.Qjly = suitid;
                                }
                            }
                        }

                        foreach (var situation in relevantSituationModel.situationList)
                        {
                            foreach (var modeItme in situation.situationList)
                            {
                                
                                if (string.IsNullOrWhiteSpace(modeItme.Qxly))
                                {
                                    modeItme.Qxly = suitid;
                                }
                            }

                            
                        }

                        foreach (var situation in relevantSituationModel.plotModelList)
                        {
                            foreach (var modeItme in situation.plotDetilModelList)
                            {

                                if (string.IsNullOrWhiteSpace(modeItme.Qjly))
                                {
                                    modeItme.Qjly = suitid;
                                }
                            }
                        }
                    }
                    //情节信息
                    if (relevantSituationModel.plotModelList.Count > 0)
                    {
                        if (crimeDataModel.plotModelList.Count > 0)
                        {
                            foreach (var plotmode in crimeDataModel.plotModelList)
                            {
                                var plotInfo = relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid);
                                if (plotInfo == null)
                                {
                                    relevantSituationModel.plotModelList.Add(plotmode);
                                }
                                else
                                {
                                    foreach (var plotDetil in plotmode.plotDetilModelList)
                                    {
                                        var plot = relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid)?.plotDetilModelList.
                                            FirstOrDefault(a => a.PlotID == plotDetil.PlotID);
                                        if (plot == null)
                                        {
                                            if (string.IsNullOrWhiteSpace(plotDetil.Qjly))
                                            {
                                                plotDetil.Qjly = suitid;
                                            }
                                            bool falg = true;
                                            foreach (var rModel in relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid).plotDetilModelList)
                                            {
                                                CaseCauseModel caseCauseModel = dALSYS_CaseCause.GetModel(rModel.PlotID);
                                                List<string> strList = caseCauseModel.AllParentId.Split(',').ToList();
                                                if (strList.Contains(plotDetil.PlotID))
                                                {
                                                    falg = false;
                                                }
                                            }
                                            CaseCauseModel caseCauseplostModel = dALSYS_CaseCause.GetModel(plotDetil.PlotID);
                                            List<string> plotstrList = new List<string>();
                                            if (caseCauseplostModel != null)
                                                plotstrList = caseCauseplostModel.AllParentId.Split(',').ToList();
                                            for (int i = 0; i < relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid).plotDetilModelList.Count; i++)
                                            {
                                                if (plotstrList.Contains(relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid).plotDetilModelList[i].PlotID) && plotDetil.PlotID != relevantSituationModel.plotModelList[0].plotDetilModelList[i].PlotID)
                                                {
                                                    relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid).plotDetilModelList.Remove(relevantSituationModel.plotModelList[0].plotDetilModelList[i]);
                                                }
                                            }
                                            if (falg)
                                            {
                                                relevantSituationModel.plotModelList.FirstOrDefault(a => a.zmid == plotmode.zmid).plotDetilModelList.Add(plotDetil);
                                            }
                                        }
                                        else
                                        {
                                            if (string.IsNullOrEmpty(plot.Qjrdjg) || plot.Qjrdjg == "1")
                                            {
                                                plot.Qjrdjg = plotDetil.Qjrdjg;
                                            }
                                            if (string.IsNullOrWhiteSpace(plot.Qjly))
                                            {
                                                plot.Qjly = plotDetil.Qjly;
                                                if (string.IsNullOrWhiteSpace(plot.Qjly))
                                                {
                                                    plot.Qjly = suitid;
                                                }
                                            }

                                            if (string.IsNullOrWhiteSpace(plot.Influencetypeid))
                                            {
                                                plot.Influencetypeid = plotDetil.Influencetypeid;
                                            }

                                            if (string.IsNullOrWhiteSpace(plot.PoType))
                                            {
                                                plot.PoType = plotDetil.PoType;
                                            }

                                            if (string.IsNullOrWhiteSpace(plot.ewid))
                                            {
                                                plot.ewid = plotDetil.ewid;
                                            }
                                            if (string.IsNullOrWhiteSpace(plot.PlotName))
                                                plot.PlotName = plotDetil.PlotName;
                                            if (plotDetil.plotOrgtextList.Any())
                                            {
                                                if (plot.plotOrgtextList == null)
                                                {
                                                    plot.plotOrgtextList = new List<PlotDetilOrgtext>();
                                                }
                                                var exceptList = plotDetil.plotOrgtextList.Where(x => !plot.plotOrgtextList.Any(p => p.Orgtext == x.Orgtext)).ToList();
                                                foreach (var item in exceptList)
                                                {
                                                    if (plot.plotOrgtextList.FirstOrDefault(a => a.Orgtext == item.Orgtext) == null)
                                                    {
                                                        plot.plotOrgtextList.Add(item);
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        relevantSituationModel.plotModelList.AddRange(crimeDataModel.plotModelList);
                    }
                    //情形信息
                    if (relevantSituationModel.situationList.Count > 0)
                    {
                        if (crimeDataModel.situationList.Count > 0)
                        {
                            foreach (var sitation in crimeDataModel.situationList)
                            {
                                var suituationInfo = relevantSituationModel.situationList.FirstOrDefault(a => a.zmid == sitation.zmid);
                                if(suituationInfo==null)
                                {
                                    relevantSituationModel.situationList.Add(sitation);
                                }
                                else
                                {
                                    foreach (var situationDetil in sitation.situationList)
                                    {

                                        var suituation = relevantSituationModel.situationList.FirstOrDefault(a => a.zmid == sitation.zmid)?.situationList.
                                            FirstOrDefault(a => a.SituationID == situationDetil.SituationID);
                                        if (suituation == null)
                                        {
                                            if (string.IsNullOrWhiteSpace(situationDetil.Qxly))
                                            {
                                                situationDetil.Qxly = suitid;
                                            }
                                            if (relevantSituationModel.situationList.Exists(a => a.zmid == sitation.zmid))
                                            {
                                                bool falg = true;
                                                foreach (var rModel in relevantSituationModel.situationList.FirstOrDefault(a => a.zmid == sitation.zmid)?.situationList)
                                                {
                                                    CaseCauseModel caseCauseModel = dALSYS_CaseCause.GetModel(rModel.SituationID);
                                                    List<string> strList = caseCauseModel.AllParentId.Split(',').ToList();
                                                    if (strList.Contains(situationDetil.SituationID))
                                                    {
                                                        falg = false;
                                                    }
                                                }
                                                if (falg)
                                                {
                                                    relevantSituationModel.situationList.FirstOrDefault(a => a.zmid == sitation.zmid)?.situationList.Add(situationDetil);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (string.IsNullOrEmpty(suituation.Qxly))
                                            {
                                                suituation.Qxly = situationDetil.Qxly;
                                                if (string.IsNullOrWhiteSpace(suituation.Qxly))
                                                {
                                                    suituation.Qxly = suitid;
                                                }

                                            }
                                            if (string.IsNullOrWhiteSpace(suituation.Qxrdjg) || situationDetil.Qxrdjg == "1")
                                            {
                                                suituation.Qxrdjg = situationDetil.Qxrdjg;
                                            }
                                            if (string.IsNullOrWhiteSpace(suituation.SituationName))
                                            {
                                                suituation.SituationName = situationDetil.SituationName;
                                            }
                                            if (situationDetil.situationOrgtextList.Any())
                                            {
                                                if (suituation.situationOrgtextList == null)
                                                {
                                                    suituation.situationOrgtextList = new List<SituationDetilOrgtext>();
                                                }
                                                var exceptList = situationDetil.situationOrgtextList.Where(x => !suituation.situationOrgtextList.Any(p => p.Orgtext == x.Orgtext)).ToList();
                                                foreach (var item in exceptList)
                                                {
                                                    if (suituation.situationOrgtextList.FirstOrDefault(a => a.Orgtext == item.Orgtext) == null)
                                                    {
                                                        suituation.situationOrgtextList.Add(item);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                
                            }
                        }
                    }
                    else
                    {
                        relevantSituationModel.situationList.AddRange(crimeDataModel.situationList);
                    }
                }
                else
                {
                    relevantSituationModelList.Add(crimeDataModel);
                }
            }
        }


        /// <summary>
        /// 获取案由要素中的情形情节
        /// </summary>
        /// <returns></returns>
        public SituationPlotResultModel ObtainSituationPlot(List<DataModel> dataModelList)
        {
            SituationPlotResultModel situationPlotResultModel = new SituationPlotResultModel();

            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            //获取犯罪行为情形情节
            //List<DataModel> crimeDataModelList = dataModelList.Where(a => a.XmlPath.IndexOf("犯罪行为相关情形") > -1)?.ToList();

            //获取相关情形情节节点信息
            List<DataModel> relevantDataModelList = dataModelList.Where(a => a.XmlPath.IndexOf("相关情形情节") > -1)?.ToList();

            //犯罪行为情形情节存在则进行合并否则不执行
            if (relevantDataModelList != null && relevantDataModelList.Count > 0)
            {
                List<SituationPlotDataModel> crimeSituationModelList = new List<SituationPlotDataModel>();
                List<SituationPlotDataModel> relevantSituationModelList = new List<SituationPlotDataModel>();
                //DataModel crimeRootDataModel = crimeDataModelList.FirstOrDefault(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "犯罪行为相关情形");
                DataModel relevantDataMode = relevantDataModelList.FirstOrDefault(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "相关情形情节");
                if (relevantDataMode != null)
                {
                    List<DataModel> relevantDetildataModelList = relevantDataModelList.Where(a => a.ParentId == relevantDataMode.ID)?.ToList();
                    if (relevantDetildataModelList != null)
                    {
                        foreach (DataModel detilDataModel in relevantDetildataModelList)
                        {
                            SituationPlotDataModel situationPlotDataModel = new SituationPlotDataModel();
                            List<DataModel> dataRModelList = xmlUtilCommon.SubordinateDataModelList(relevantDataModelList, detilDataModel);
                            XmlDocument xmlDocument = xmlUtilCommon.DataModelByXml(dataRModelList, detilDataModel.ParentId);
                            SituationModel situationModel = XmlUtility.DeserializeToObject<SituationModel>(xmlDocument.OuterXml);
                            situationPlotDataModel.situationModel = situationModel;

                            situationPlotDataModel.parndPath = relevantDataMode.XmlPath.Replace(dataContext.DataLayerAns.CaseCausesList[0].CC_Name + "/" + dataContext.DataLayerAns.CaseCausesList[0].CC_Name, dataContext.DataLayerAns.CaseCausesList[0].CC_Name);
                            situationPlotDataModel.dataModelList = dataRModelList;
                            situationPlotDataModel.XmlDocument = xmlUtilCommon.DataModelByXml(dataRModelList, detilDataModel.ParentId);
                            relevantSituationModelList.Add(situationPlotDataModel);
                        }
                    }

                }
                situationPlotResultModel.crimeDataModelList = crimeSituationModelList;
                situationPlotResultModel.relevantDataModelList = relevantSituationModelList;
            }

            return situationPlotResultModel;
        }
    }

    /// <summary>
    /// 情形情节实体
    /// </summary>
    public class SituationPlotResultModel
    {
        /// <summary>
        /// 犯罪行为情形情节
        /// </summary>
        public List<SituationPlotDataModel> crimeDataModelList = new List<SituationPlotDataModel>();

        /// <summary>
        /// 相关情形情节
        /// </summary>
        public List<SituationPlotDataModel> relevantDataModelList = new List<SituationPlotDataModel>();
    }

    public class SituationPlotDataModel
    {
        /// <summary>
        /// 情形情节信息
        /// </summary>
        public SituationModel situationModel;
 

        public string parndPath;
        /// <summary>
        /// 案件实体集合
        /// </summary>
        public List<DataModel> dataModelList;

        /// <summary>
        /// 情形情节节点信息
        /// </summary>
        public XmlDocument XmlDocument;
    }


}
